package me.chan.graph;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by JanGin on 2020/4/23.
 */
public class Bag<V> implements Iterable<V> {


    private Node<V> first;  // first element of bag
    private int count;       // number of elements in bag


    private static class Node<V> {
        private V v;
        private Node<V> next;

    }

    public Bag() {
        this.first = null;
        this.count = 0;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return count;
    }

    public void add(V v) {
        Node<V> oldfirst = first;
        first = new Node<V>();
        first.v = v;
        first.next = oldfirst;
        ++count;
    }

    @Override
    public Iterator<V> iterator() {
        return new ListIterator<V>(first);
    }

    private class ListIterator<V> implements Iterator<V> {
        private Node<V> current;

        public ListIterator(Node<V> first) {
            current = first;
        }

        public boolean hasNext() {
            return current != null;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        public V next() {
            if (!hasNext()) throw new NoSuchElementException();
            V item = current.v;
            current = current.next;
            return item;
        }
    }
}
